package com.skylin.mysell.service.impl;

import com.skylin.mysell.SellException;
import com.skylin.mysell.converter.OrderMaster2OrderDto;
import com.skylin.mysell.dto.CartDTO;
import com.skylin.mysell.dto.OrderDTO;
import com.skylin.mysell.entities.OrderDetail;
import com.skylin.mysell.entities.OrderMaster;
import com.skylin.mysell.entities.ProductInfo;
import com.skylin.mysell.enums.OrderStatusEnum;
import com.skylin.mysell.enums.PayStatusEnum;
import com.skylin.mysell.enums.ResultEnum;
import com.skylin.mysell.repository.OrderDetailRepository;
import com.skylin.mysell.repository.OrderMasterRepository;
import com.skylin.mysell.service.OrderService;
import com.skylin.mysell.service.ProductInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * @author quanlinlin on 2018/12/20 22:24.
 * @version 1.0
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository OrderMasterRepository;

    @Override
    @Transactional(rollbackFor = {})
    public OrderDTO create(OrderDTO orderDTO) {
        /**
         * 1.查询商品数量和价格
         * 2.计算总价
         * 3.写入订单数据库
         * 4.扣库存
         */
        UUID orderId = UUID.randomUUID();
        BigDecimal orderAmount = new BigDecimal(0);
        List<OrderDetail> orderDetailList = orderDTO.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            ProductInfo one = productInfoService.findOne(orderDetail.getProductId());
            Optional.of(one).orElseThrow(() -> new SellException(ResultEnum.PRODUCT_NOT_EXIST));
            orderAmount = one.getProductPrice().multiply(BigDecimal.valueOf(orderDetail.getProductQuantity())).add(orderAmount);
            orderDetail.setDetailId(UUID.randomUUID().toString());
            orderDetail.setOrderId(orderId.toString());
            BeanUtils.copyProperties(one, orderDetail);
            orderDetailRepository.save(orderDetail);
        }

        //写入数据库
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId.toString());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW_ORDER.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        OrderMasterRepository.save(orderMaster);

        //扣除库存
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().
                map(orderDetail -> new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity())).collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        Optional<OrderMaster> orderMaster = OrderMasterRepository.findById(orderId);
        if (orderMaster.get() == null) {
            throw new SellException(ResultEnum.ORDER_NOT_EXIST);
        }

        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster.get(), orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);

        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        Page<OrderMaster> orderMasterPage = OrderMasterRepository.findByBuyerOpenid(buyerOpenid, pageable);
        List<OrderDTO> orderDTOList = OrderMaster2OrderDto.convert(orderMasterPage.getContent());
        Page<OrderDTO> orderDTOPage = new PageImpl<>(orderDTOList, pageable, orderMasterPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    @Transactional(rollbackFor = {})
    public OrderDTO cancel(OrderDTO orderDTO) {
        //判断订单状态，已完结的订单不能取消
        //修改订单状态
        //返回库存
        //如果已支付，需要退款
        OrderMaster orderMaster = new OrderMaster();

        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW_ORDER.getCode())) {
            log.error("{取消订单} 订单状态不正确，OrderId={}，OrderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }
        orderDTO.setOrderStatus(OrderStatusEnum.CANCELED.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = OrderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("{取消订单} 更新失败，orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }

        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("{取消订单} 订单中无商品详情，orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_DETAIL_EMPTY);
        }


        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream().map(orderDetail -> new CartDTO(orderDetail.getProductId(), orderDetail.getProductQuantity())).collect(Collectors.toList());
        productInfoService.increaseStock(cartDTOList);

        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            //todo 退款
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        //判断订单状态
        //修改订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW_ORDER.getCode())) {
            log.error("{完结订单} 订单状态不正确，OrderId={}，OrderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = OrderMasterRepository.save(orderMaster);
        if (result == null) {
            log.error("{完结订单} 更新失败，orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW_ORDER.getCode())) {
            log.error("{支付订单} 订单状态不正确，OrderId={}，OrderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new SellException(ResultEnum.ORDER_STATUS_ERROR);
        }

        //判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("{支付订单} 订单状态不正确，orderDTO={}", orderDTO);
            throw new SellException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改支付状态
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster result = OrderMasterRepository.save(orderMaster);
        if (result == null) {
            log.error("{支付订单} 更新失败，orderMaster={}", orderMaster);
            throw new SellException(ResultEnum.ORDER_UPDATE_ERROR);
        }
        return orderDTO;
    }
}
